package com.test.base.netty_upgrade.httpserver;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * description
 * 创建一个httpServer然后让浏览器获取响应到的请求（http协议在netty的使用）
 * @author zken
 * @CreateDate 2024/11/20 21:28:32
 */
@Slf4j
public class CreateHttpServer {
    public static void main(String[] args) {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        ServerBootstrap server = new ServerBootstrap();
        server.group(boss, worker);
        server.channel(NioServerSocketChannel.class);
        server.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                // 因为是读事件，所以是读入
                ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
                // http解码器，即是出队处理器也是入队处理器
                ch.pipeline().addLast(new HttpServerCodec());
                // 获取server获得到的信息
                ch.pipeline().addLast(new SimpleChannelInboundHandler<HttpRequest>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
                        // 获取请求的uri
                        log.info(msg.uri());
                        // 返回响应
                        DefaultFullHttpResponse response = new DefaultFullHttpResponse(msg.protocolVersion(), HttpResponseStatus.OK);
                        //书写响应体
                        String content = "<h1>Hello World!!!</h1>";
                        // 设置响应内容大小，告知请求端请求的大小，让请求段知晓何时请求结束
                        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.length());
                        response.content().writeBytes(content.getBytes());
                        ctx.writeAndFlush(response);
                    }
                });
             /*   ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        log.debug("{}", msg.getClass());
                    }
                });*/
            }
        });

        ChannelFuture channelFuture = null;
        try {
            channelFuture = server.bind(8080).sync();
            channelFuture.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace(System.err);
            log.error("server error");
        }
    }
}
